# -*- coding: utf-8 -*-
"""
Created on Sun Feb  3 19:28:45 2019
windows7
python3.6.3
Anaconda3->spyder
opencv3.4.5
代码参考《OpenCV3计算机视觉 Python语言实现》（第二版）
@author: Administrator
"""

import cv2
import numpy as np
#from scipy import ndimage

print(cv2.__version__)                    # 查看opencv的版本

img = cv2.imread('pycv.png')
#复制原图，避免原图被改变
imgk3 = img.copy()
imgk5 = img.copy()
imgk2_3 =img.copy()

#3x3卷积核
#数组数据总和越大处理后图像就越亮，越小就越暗
kernel_3x3 = np.array([[-1,-1,-1],
                       [-1,9,-1],
                       [-1,-1,-1]])

#5x5滤波模糊核
#数组数据总和为1
kernel_5x5 = np.array([[0.04,0.04,0.04,0.04,0.04],
                       [0.04,0.04,0.04,0.04,0.04],
                       [0.04,0.04,0.04,0.04,0.04],
                       [0.04,0.04,0.04,0.04,0.04],
                       [0.04,0.04,0.04,0.04,0.04]])
#不对称的卷积核,效果类似油画
kernel2_3x3 = np.array([[-2,-1, 0],
                        [-1, 1, 1],
                        [ 0, 1, 2]]) 

"""
进行卷积，对每个通道使用相同的卷积核进行处理；
若要不同通道使用不同的卷积核就要使用cv2.split()跟cv2.merge()
"""
#-1表示处理后的图像深度与原图相同
imgk3 = cv2.filter2D(imgk3,-1,kernel_3x3)
imgk5 = cv2.filter2D(imgk5,-1,kernel_5x5)
imgk2_3 = cv2.filter2D(imgk2_3,-1,kernel2_3x3)

#提取边缘
imgk3_1 = img - imgk3
imgk5_1 = img - imgk5
imgk2_3_1 = img - imgk2_3

cv2.imshow('imgk3_1',imgk3_1)
cv2.imshow('imgk5_1',imgk5_1)
cv2.imshow('imgk2_3_1',imgk2_3_1)

'''使用cv2.Canny直接检测边缘'''
#后两个参数分别是最小阈值和最大阈值
#图像中大于最大阈值的被认为是边界，
#小于最大阈值但是与被认为是边界的线段相连的，也被认为是边界。
imgC2 = cv2.Canny(img,100,600)
print(imgC2.shape)        # 查看图像的宽高
cv2.imshow('canny',imgC2) # 图像边缘是白色，其余为黑色

"""
将边缘变成黑色，其他无关部分变成白色
"""
imgC3 = imgC2.copy()
for i in range(518):
    for j in range(786):
        if imgC3[i,j] == 0:  # 这是针对单通道的，多通道的要用[i,j,0/1/2]
            imgC3[i,j] = 255
        else:
            imgC3[i,j] = 0
cv2.imshow('canny2',imgC3)

cv2.waitKey()
cv2.destroyAllWindows()




